package paolo.android.bookloc;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.AdapterView;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class BookLoc extends Activity {
	Cursor locations = null;
	LocationAdapter adapter = null;
	
	EditText name = null;
	EditText address = null;
	RadioGroup types = null;
	EditText notes = null;
	
	Location current = null;
	
	int progress;
	AtomicBoolean isActive = new AtomicBoolean(true);
	
	SQLiteDatabase db = null;
	
	public final static String ID_EXTRA = "paolo.android.bookloc._ID";
	
	SharedPreferences prefs = null;
	ListView list = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main);

        db = (new LocationSQLiteHelper(this)).getWritableDatabase();
        
        name = (EditText)findViewById(R.id.name);
        address = (EditText)findViewById(R.id.addr);
        types = (RadioGroup)findViewById(R.id.types);
        notes = (EditText)findViewById(R.id.notes);
        
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(prefListener);
        
        list = (ListView)findViewById(R.id.locations);
        list.setOnItemClickListener(onListClick);
        initList();
        
    }
    
    private void initList() {
    	if (locations != null) {
    		stopManagingCursor(locations);
    		locations.close();
    	}
    	
    	locations = Location.getAll(db, prefs.getString("sort_order", ""));
    	startManagingCursor(locations);
    	adapter = new LocationAdapter(locations);
    	list.setAdapter(adapter);
    }
	
	private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			
			Intent i = new Intent(BookLoc.this, DetailForm.class);
			i.putExtra(ID_EXTRA, String.valueOf(id));
			startActivity(i);
			
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.option, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.add) {
			startActivity(new Intent(this, DetailForm.class));
			
			return true;
		}
		else if (item.getItemId() == R.id.run) {
			setProgressBarVisibility(true);
			progress = 0;
			startWork();
			
			return true;
		}
		else if (item.getItemId() == R.id.prefs) {
			startActivity(new Intent(this, EditPreferences.class));
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void doSomeLongWork(final int incr) {
		runOnUiThread(new Runnable() {
			public void run() {
				progress += incr;
				setProgress(progress);
			}
		});
		
		SystemClock.sleep(250);
	}
	
	private Runnable longTask = new Runnable() {
		public void run() {
			for (int i = 0; i < 10000 && isActive.get(); i+=200) {
				doSomeLongWork(200);
			}
			
			if (isActive.get()) {
				runOnUiThread(new Runnable() {
					public void run () {
						setProgressBarVisibility(false);
						progress = 0;
					}
				});
			}
		}
	};
	
	private SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) {
			if (key.equals("sort_order")) {
				runOnUiThread(new Runnable() {
					public void run() {
						initList();
					}
				});
			}
		}
	};
	
	private void startWork() {
		setProgressBarVisibility(true);
		new Thread(longTask).start();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		
		isActive.set(false);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		isActive.set(true);
		
		if (progress > 0) {
			startWork();
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		
		db.close();
	}
	
	class LocationAdapter extends CursorAdapter {
		LocationAdapter(Cursor c) {
			super(BookLoc.this, c);
		}
		
		@Override
		public void bindView(View row, Context ctxt, Cursor c) {
			LocationWrapper wrapper = (LocationWrapper)row.getTag();
			wrapper.populateFrom(c);
		}
		
		@Override
		public View newView(Context ctxt, Cursor c, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.row, parent, false);
			LocationWrapper wrapper = new LocationWrapper(row);
			
			row.setTag(wrapper);
			wrapper.populateFrom(c);
			
			return row;
		}
		
	}
	
	class LocationWrapper {
		private TextView name = null;
		private TextView address = null;
		private ImageView icon = null;
		private View row = null;
		
		LocationWrapper(View row) {
			this.row = row;
		}
		
		void populateFrom(Cursor c) {
			getName().setText(c.getString(c.getColumnIndex("name")));
			getAddress().setText(c.getString(c.getColumnIndex("address")));
			String type = c.getString(c.getColumnIndex("type"));

			
			if (type.equals("store")) {
				getIcon().setImageResource(R.drawable.icostore);
			}
			else if (type.equals("food")) {
				getIcon().setImageResource(R.drawable.icofood);
			}
			else {
				getIcon().setImageResource(R.drawable.icoperson);
			}
			
		}
		
		TextView getName() {
			if (name == null) {
				name = (TextView)row.findViewById(R.id.title);
			}
			
			return name;
		}
		
		TextView getAddress() {
			if (address == null) {
				address = (TextView)row.findViewById(R.id.address);
			}
			
			return address;
		}
		
	
		ImageView getIcon() {
			if (icon == null) {
				icon = (ImageView)row.findViewById(R.id.icon);
			}
			
			return icon;
		}
	
	}
}